package com.hub.netty.client.config;


import com.hub.netty.base.config.NettyProperties;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ author 令狐冲
 * @ date & time 2025/2/6 15:19
 */
@Configuration
@RequiredArgsConstructor
public class NettyConfig {

    private final NettyProperties nettyProperties;

    /**
     * 客户端启动器
     *
     * @return
     */
    @Bean
    public Bootstrap bootstrap() {
        // 新建一组线程池
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup(nettyProperties.getBoss());

        return new Bootstrap()
                // 指定线程组
                .group(eventExecutors)
                .option(ChannelOption.SO_KEEPALIVE, true)
                // 指定通道
                .channel(NioSocketChannel.class)
                // 指定处理器
                .handler(new NettyClientHandler());
    }

    @Bean
    public NettyChannelFactory channelFactory(Bootstrap bootstrap) {
        return new NettyChannelFactory(bootstrap);
    }

    @Bean
    public NettyChannelPool channelPool(NettyChannelFactory factory) {
        return new NettyChannelPool(factory, nettyProperties);
    }
}
